const { Worker, isMainThread, parentPort } = require("worker_threads");
const os = require("os");
const colors = require("colors");
const EventEmitter = require("events").EventEmitter;
const { defaultThreadCount, workerPath, frequency } = require("./config");

class MyEmitter extends EventEmitter {}
// const vm = require("vm");
class WorkerThread {
  taskQuery = [];

  /** @type{Worker[]} */
  workerQuery = [];
  threadCount = process.argv[2] || defaultThreadCount;
  // workerQueryCount = 0
  totalCount = 0;
  loopMonitor = 0;

  isMasterThreadExit = false;
  /** @type {EventEmitter} */
  eventET = new MyEmitter();
  constructor() {
    //   console.log(`cpus:${colors.cyan(this.cpus)}`)
    for (let i = 0; i < this.threadCount; i++) {
      this.createWorker();
    }
    this.events();
    // this.eventLoop();
  }

  add(params) {
    this.taskQuery.push(params);
    return this;
  }

  createWorker() {
    //保存fork返回的进程实例
    const worker = new Worker(workerPath);
    //监听子进程exit事件
    worker.on("exit", (code, signal) => {
      if (code !== null && signal === null) {
        // console.log("worker:" + worker.pid + "exited");
        console.log(
          `worker:子进程${colors.cyan(worker.threadId)}${colors.red(
            "异常退出,已尝试重启中..."
          )}`
        );
        delete this.workerQuery[
          this.workerQuery.findIndex((i) => i.threadId === worker.threadId)
        ];
        this.createWorker();
      } else {
        console.log(`worker:子进程${colors.cyan(worker.pid)}正常退出`);
      }
    });

    worker.on("message", ({ status, data }) => {
      this.workerQuery.push(worker);
      console.log(
        `worker:子进程${colors.cyan(worker.threadId)}收到消息:${colors.cyan(
          data
        )}`
      );
      // if(status === 200 && toString.call(data) === '[object Object]'){
      //   this.eventET.emit("taskMessage",data)
      // }else{
      //   this.eventET.emit("taskMessage",false)
      // }
    });

    this.workerQuery.push(worker);
    console.log("Create worker:" + colors.cyan(worker.threadId));
  }

  stop() {
    clearInterval(this.loopMonitor);
    return this;
  }

  events() {
    process.on("exit", () => {
      this.isMasterThreadExit = true;
      console.log(`worker:${colors.cyan(process.pid)}主线程退出`);
      // for (const worker of this.workerQuery) {
      //   worker.
      // }

      this.workerQuery = [];

      clearInterval(this.loopMonitor);
    });
  }

  // /**
  //  *
  //  * @param {Function} cb
  //  */
  // PostMessage(cb){
  //   const _this = this;
  //   this.eventET.on("taskMessage",function(data){
  //     _this.totalCount++
  //     cb.call(this,data,_this.totalCount)
  //   })
  // }

  /**
   * @description 事件循环
   */
  run() {
    if (this.loopMonitor !== 0) clearInterval(this.loopMonitor);

    this.totalCount = 0;

    this.loopMonitor = setInterval(() => {
      if (!this.isMasterThreadExit) {
        //确保任务队列和线程池都有数据
        if (this.taskQuery.length !== 0 && this.workerQuery.length !== 0) {
          const task = this.taskQuery.shift();
          const worker = this.workerQuery.shift();
          worker.postMessage(task);
        }
        // if(this.taskQuery.length === 0){
        //   this.eventET.emit("taskMessage","complete")
        // }
      } else {
        clearInterval(this.loopMonitor);
      }
    }, 100);

    return this;
  }
}

module.exports = WorkerThread;
